/**
 * Created by admin on 2016/8/9.
 */
var crypto = require('crypto');
var request = require('request');
var redis = require("redis");


var SEAGOUHOST = 'seagou.lovepinyao.com';
var HMHOST = 'healthManager.lovepinyao.com';
var PARSE_HOST = 'https://parse.lovepinyao.com/parse';
var redis_port = 6379;
var redis_host = "120.55.114.198";
var IMAGE_FEX = 'http://7xlaxq.com1.z0.glb.clouddn.com/';
var DEFAULT_AVATAR = 'Fr6ubXxHmEiMm3D9mKivMEND2JUG';
var DEFAULT_BACKGROUD = 'FidFrm0VMBRN0sydBe1ukHGdVk8g';

var PARSE_HEADERS = {
    'Content-Type': 'application/json;charset=utf-8',
    'X-Parse-Application-Id': 'myAppId',
    'X-Parse-Master-Key': 'masterKey'
};

var getJADE = function () {
    return {
        __PLUGINS_ROOT__: '/dist/assets/plugins',
        __BOWER_ROOT__: '/bower_components',
        __CSS_ROOT__: '/dist/assets/css',
        __JS_ROOT__: '/dist/assets/js',
        __IMAGES_ROOT__: '/dist/assets/images',
        __COMPRESSED_SUFFIX__:".min"
    };
};

// 返回接口
var response_sms = function (code, message, data) {
    return JSON.stringify({'code': code, 'message': message, 'results': data});
};

var check_parms = function (parms) {
    var hasNull = false;
    for (var i=0; i<parms.length; i++){
        if (!parms[i]){
            hasNull = true;
        }
    }
    return hasNull;
};

var obj2dic = function (obj, fields) {

    Date.prototype.Format = function(fmt)
    { //author: meizz
        var o = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours(),                   //小时
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        return fmt;
    };

    var temp = {};
    for (var i=0; i<fields.length; i++){
        // var obj_temp = obj.get(fields[i]);
        // if (typeof obj_temp == 'undefined'){
        //     temp[fields[i]] = null;
        // }else {
            temp[fields[i]] = obj.get(fields[i]);
        // }
    }
    temp['objectId'] = obj.id;
    return temp;
};

var obj2dicCoupon = function (obj, fields) {

    Date.prototype.Format = function(fmt)
    { //author: meizz
        var o = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours(),                   //小时
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        return fmt;
    };

    var temp = {};
    for (var i=0; i<fields.length; i++){
        temp[fields[i]] = obj.get(fields[i]);
         if(typeof temp[fields[i]] == 'object'){
             temp[fields[i]] = temp[fields[i]].Format('yyyy-MM-dd');
         }
    }
    temp['objectId'] = obj.id;
    return temp;
};

var apiRequest = function (url,data) {
    if(!data){
        return new Promise(
            function(resolve,reject){
                request(url,function(error,response,body){
                    if(error){
                        reject(error);
                    }else{
                        try{
                            var responseJSON = JSON.parse(body);
                        }catch(e){
                            reject(error);
                        }
                        resolve(responseJSON);
                    }
                });
            }
        );
    }else{
        var options = {
            url:url,
            method:'POST',
            form:data,
            headers: {
                'X-Access-Code':'lovepinyaoaccesscode',
                'X-Access-Key':'lovepinyaoaccesskey'
            }
        };
        return new Promise(
            function(resolve,reject){
                request(options,function(error,response,body){
                    if(error){
                        reject(error);
                    }else{
                        try{
                            var responseJSON = JSON.parse(body);
                        }catch(e){
                            reject(error);
                        }
                        resolve(responseJSON);
                    }
                });
            }
        );
    }
};

var apiHMRequest = function(method,path,params){

    var requestSign = createdSign(params);

    var options = {
        url: HM_HOST + path,
        method:method,
        headers: HM_HEADERS
    };
    if(method.toUpperCase() == 'POST') {
        options.body = JSON.stringify(params);
        options.form = params;
    }else{
        if(method.toUpperCase() == 'GET'){
            options.url += '?'+qs.stringify(params);
        }else{
            options.body = JSON.stringify(params);
            options.form = params;
        }
    }
    //加上请求签名
    options.headers['X-Request-Sign'] = requestSign;
    return new Promise(
        function(resolve,reject){
            request(options,function(error,response,body){
                if(error){
                    reject(error);
                }else{
                    try{
                        var responseJSON = JSON.parse(body);
                    }catch(e){
                        reject(error);
                    }
                    resolve(responseJSON);
                }
            });
        }
    )
};

var apiParseRequest = function(method,path,params,X_Session_Token,env){
    if(env && env == 'test'){
        PARSE_HOST = 'http://test.parse.lovepinyao.com/parse'
    }
    var options = {
        url: PARSE_HOST + path,
        method:method,
        body:JSON.stringify(params),
        form:params,
        headers: PARSE_HEADERS
    };
    if(X_Session_Token){
        options.headers['X-Parse-Session-Token'] = X_Session_Token;
        options.headers['X-Parse-MasterKey'] = 'masterKey';
    }
    return new Promise(
        function(resolve,reject){
            request(options,function(error,response,body){
                console.log(error,body);
                if(error){
                    reject(error);
                }else{
                    try{
                        var responseJSON = JSON.parse(body);
                    }catch(e){
                        reject(error);
                    }
                    resolve(responseJSON);
                }
            });
        }
    )
};

function Base64() {

    // private property
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    };

    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    };

    // private method for UTF-8 encoding
    _utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    };

    // private method for UTF-8 decoding
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

// 包装下返回json格式
var con2json = function (code, message, content) {
    var response = {'code': code, 'message': message};
    if (typeof content != 'undefined'){
        response['results'] = content;
    }
    return response;
};
var getRedis = function () {
    var client = redis.createClient({host: redis_host, port: redis_port, db: 5});
    client.auth("PinYao123");
    client.on("error", function (err) {
        console.log("Error " + err);
    });
    return client

};
var checkAvatar = function (avatar_url) {
    if (typeof avatar_url == 'undefined' || avatar_url == ''){
        avatar_url = IMAGE_FEX + DEFAULT_AVATAR;
    }else {
        var re_http = /http:\/\//;
        if (re_http.test(avatar_url)) {
            avatar_url = avatar_url.split('/');
            avatar_url = avatar_url[avatar_url.length - 1];
        }else {
            avatar_url = IMAGE_FEX + avatar_url;
        }
    }
    return avatar_url;
};
module.exports = {
    response_sms: response_sms,
    check_parms: check_parms,
    obj2dic: obj2dic,
    obj2dicCoupon:obj2dicCoupon,
    getJADE:getJADE,
    apiHMRequest:apiHMRequest,
    apiParseRequest:apiParseRequest,
    apiRequest:apiRequest,
    base64Assert:Base64,
    con2json: con2json,
    getRedis: getRedis,
    checkAvatar: checkAvatar,
    SEAGOUHOST:SEAGOUHOST,
    HMHOST:HMHOST,
    IMAGE_FEX: IMAGE_FEX,
    DEFAULT_AVATAR: DEFAULT_AVATAR,
    DEFAULT_BACKGROUND: DEFAULT_BACKGROUD

};